#include "mprpcchannel.h"
#include "rpcheader.pb.h"
#include "mprpcapplication.h"
#include "mprpccontroller.h"
#include "zookeeperutil.h"
#include <string>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>

/*
所有的caller,通过stub代理对象调用的rpc方法,都是通过重写channel下的CallMethod方法
统一做rpc方法调用的数据序列化和网络发送
*/
// 重写RpcChannel下的CallMethod方法 
void MprpcChannel::CallMethod(const google::protobuf::MethodDescriptor* method, 
                        google::protobuf::RpcController* controller, 
                const google::protobuf::Message* request, 
                        google::protobuf::Message* response, 
                        google::protobuf::Closure* done)
{
    // 通过MethodDescriptor*获取ServiceDescriptor*
    const google::protobuf::ServiceDescriptor* svr_desc = method->service();
    // 获取服务对象名称
    std::string service_name = svr_desc->name();
    // 获取rpc方法名称
    std::string method_name = method->name();

    // 获取参数的序列化字符串长度 args_size
    uint32_t args_size = 0;
    std::string args_str;
    if (request->SerializeToString(&args_str)) {
        args_size = args_str.size();
    }
    else {
        // 因为RpcControlle::SetFailed不会涉及到成员变量的访问
        // 因此无需判断controller == nullptr
        controller->SetFailed("serialize request error!");
        return;
    }

    // header_size + service_name method_name args_size + args
    // 定义rpc的请求header
    mprpc::RpcHeader rpcHeader;
    rpcHeader.set_service_name(service_name);
    rpcHeader.set_method_name(method_name);
    rpcHeader.set_args_size(args_size);

    uint32_t header_size = 0;
    std::string rpc_header_str;
    if (rpcHeader.SerializeToString(&rpc_header_str)) {
        // 序列化rpcHeader成功
        header_size = rpc_header_str.size();
    }
    else {
        controller->SetFailed("serialize rpc header error!");
        return;
    }

    // 组织待发送rpc请求的字符串
    std::string send_rpc_str;
    send_rpc_str.insert(0, std::string((char*)&header_size, 4));  // 将header_size的二进制转化为字符串写入
    send_rpc_str += rpc_header_str;
    send_rpc_str += args_str;

    // debug
    std::cout << "\n--------------------------------" << std::endl;
    std::cout << "header_size: " << header_size << std::endl;
    std::cout << "rpc_header_str: " << rpc_header_str << std::endl;
    std::cout << "service_name: " << service_name << std::endl;
    std::cout << "method_name: " << method_name << std::endl;
    std::cout << "args_str: " << args_str << std::endl;     
    std::cout << "\n--------------------------------" << std::endl;

    // 使用tcp编程,完成rpc方法的远程调用
    int clientfd = socket(AF_INET, SOCK_STREAM, 0);
    if (clientfd < 0) {
        char errtxt[512] = {0};
        sprintf(errtxt, "create socket error! errno: %d, errmsg: %s", errno, strerror(errno));
        controller->SetFailed(errtxt); 
        return;
    }

    ZkClient zkCli;
    zkCli.Start();
    std::string method_path = "/" + service_name + "/" + method_name;
    std::string host_data = zkCli.GetData(method_path.c_str());
    if (host_data == "") {
        controller->SetFailed(method_path + " is not exist!");
        return;
    }
    int idx = host_data.find(":");
    if (idx == -1) {
        controller->SetFailed(method_path + " address is invalid!");
        return;
    }

    // 读取配置项文件rpcserver的信息
    std::string ip = MprpcApplication::GetInstance().GetConfig().Load("rpcserverip");
    uint16_t port = atoi(MprpcApplication::GetInstance().GetConfig().Load("rpcserverport").c_str());

    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    inet_aton(ip.c_str(), &(server_addr.sin_addr));

    // 连接rpc节点
    if (-1 == connect(clientfd, (struct sockaddr*)&server_addr, sizeof(server_addr))) {
        close(clientfd);
        char errtxt[512];
        sprintf(errtxt, "connect error! errno: %d errmsg: %s", errno, strerror(errno));
        controller->SetFailed(errtxt);
        return;
    }

    // 发送rpc请求
    if (-1 == send(clientfd, send_rpc_str.c_str(), send_rpc_str.size(), 0)) {
        close(clientfd);
        char errtxt[512];
        sprintf(errtxt, "send sned_rpc_str error! errno: %d errmsg: %s", errno, strerror(errno));
        controller->SetFailed(errtxt);
        return;   
    }

    // 接收rpc响应
    char recv_buf[1024] = {0};
    int recv_size = 0;
    if (-1 == (recv_size = recv(clientfd, recv_buf, 1024, 0))) {
        close(clientfd);
        char errtxt[512];
        sprintf(errtxt, "recv error! errno: %d errmsg: %s", errno, strerror(errno));
        controller->SetFailed(errtxt);
        return;
    }

    // 反序列化rpc响应
    // 出现问题,recv_buf中,\0后面的数据不会保存,所以会导致反序列化失败
    // std::string response_str(recv_buf, 0, recv_size);
    // if (!response->ParseFromString(response_str))
    if (!response->ParseFromArray(recv_buf, recv_size)) {
        close(clientfd);
        char errtxt[512];
        sprintf(errtxt, "parse error! errno: %d errmsg: %s", errno, strerror(errno));
        controller->SetFailed(errtxt);
        return;
    }

    close(clientfd);
}